let querystring = require( 'querystring' );
let request = require( 'request' );
let parseString = require( 'xml2js' ).parseString;
let { formatXmlObj } = require( '../../method' );
let config = require( '../config' );
let { getRandomString, getOutTradeNo } = require( './getQueryParams' );
let { getSign } = require('../../method');


// 将 obj 转化为 xml 对象
formatXml = obj => {
  let keys = Object.keys( obj );
  let result = '<xml>';
  keys.forEach( function ( key ) {
    result += '<' + key + '>' + obj[ key ] + '</' + key + '>';
  } );
  result += '</xml>';
  return result;

};


// 调用统一支付接口
// 返回一个从微信后台返回的一个 xml 信息
const invokeUniformApi = ( total_fee, openid, spbill_create_ip = '' ) => {
  return new Promise( ( resolve, reject ) => {

    let { prepay_id_url, appid, mch_id, notify_url, trade_type, api_key } = config;


    //取得需向微信服务器发送的数据,且通过该数据组进行xml与sign数据生成
    //数据集必须包含所有微信端所必须的字段数据信息
    let nonce_str = getRandomString();
    let out_trade_no = getOutTradeNo();
    let body = 'test';

    let qStrObjPart = {
      'appid': appid,
      'mch_id': mch_id,
      'nonce_str': nonce_str,
      'body': body,
      'out_trade_no': out_trade_no,
      'total_fee': total_fee,
      'trade_type': trade_type,
      'notify_url': notify_url,
      'spbill_create_ip': spbill_create_ip,
      'openid': openid,
    };

    // 加入签名, 产生完整数据集
    let qStrObj = {
      ...qStrObjPart,
      'sign': getSign( qStrObjPart, api_key )
    };

    // 将数据集转化为 xml 数据
    let xml = formatXml( qStrObj );


    let params = {
      url: prepay_id_url,
      method: 'POST',
      body: xml
    };

    request( params, ( error, response, body ) => {
      // console.log( params, '请求参数拉拉' );
      // console.log( 'error:', error );
      // console.log( 'statusCode:', response && response.statusCode );
      if ( error ) {
        reject( statusCode + ': ' + error );
      } else {
        if ( body ) {
          // 将xml 格式转化为 object
          parseString( body, function ( err, result ) {
            if ( err ) reject( err );
            let { xml: xmlObj } = result;
            if ( !xmlObj ) reject( '生成订单, 无法解析微信返回的xml数据' );


            xmlObj = formatXmlObj(xmlObj);

            // 加入交易号, 后面在微信会通知该交易号是否已经完成交易
            xmlObj.out_trade_no = out_trade_no;

            resolve( xmlObj);


          } );
        } else {
          reject( 'I cant not get the openid, wu wu wu !' );
        }
      }

    } );
  } );

};


module.exports = invokeUniformApi;